This week’s exercise is about cluster analysis and classification. Tasks include:
Setting working path, loading library and data set.
#Setting working path
setwd("/home/ls/R/projekteja/IODS-project/")
# access the MASS package
library(MASS)
# load the data
data("Boston")
Boston data is included in the MASS package. Data is about housing values in suburbs of Boston city, with other demographic and environmental information as well. Further information: https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/Boston.html.
List of variables (from above url):
| Variable name | Definition |
|---|---|
| crim | per capita crime rate by town. |
| zn | proportion of residential land zoned for lots over 25,000 sq.ft. |
| indus | proportion of non-retail business acres per town. |
| chas | Charles River dummy variable (= 1 if tract bounds river; 0 otherwise). |
| nox | nitrogen oxides concentration (parts per 10 million). |
| rm | average number of rooms per dwelling. |
| age | proportion of owner-occupied units built prior to 1940. |
| dis | weighted mean of distances to five Boston employment centres. |
| rad | index of accessibility to radial highways. |
| tax | full-value property-tax rate per $10,000. |
| ptratio | pupil-teacher ratio by town. |
| black | 1000(Bk - 0.63)\(^{2}\) where Bk is the proportion of blacks by town. |
| lstat | lower status of the population (percent). |
| medv | median value of owner-occupied homes in $1000s. |
Sources:
- Harrison, D. and Rubinfeld, D.L. (1978) Hedonic prices and the demand for clean air. J. Environ. Economics and Management 5, 81–102.
- Belsley D.A., Kuh, E. and Welsch, R.E. (1980) Regression Diagnostics. Identifying Influential Data and Sources of Collinearity. New York: Wiley.
Loading library dplyr for further DM needs.
library(dplyr)
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
##
## select
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
#Data dimensions, variable names and some values.
glimpse(Boston)
## Rows: 506
## Columns: 14
## $ crim <dbl> 0.00632, 0.02731, 0.02729, 0.03237, 0.06905, 0.02985, 0.08829…
## $ zn <dbl> 18.0, 0.0, 0.0, 0.0, 0.0, 0.0, 12.5, 12.5, 12.5, 12.5, 12.5, …
## $ indus <dbl> 2.31, 7.07, 7.07, 2.18, 2.18, 2.18, 7.87, 7.87, 7.87, 7.87, 7…
## $ chas <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ nox <dbl> 0.538, 0.469, 0.469, 0.458, 0.458, 0.458, 0.524, 0.524, 0.524…
## $ rm <dbl> 6.575, 6.421, 7.185, 6.998, 7.147, 6.430, 6.012, 6.172, 5.631…
## $ age <dbl> 65.2, 78.9, 61.1, 45.8, 54.2, 58.7, 66.6, 96.1, 100.0, 85.9, …
## $ dis <dbl> 4.0900, 4.9671, 4.9671, 6.0622, 6.0622, 6.0622, 5.5605, 5.950…
## $ rad <int> 1, 2, 2, 3, 3, 3, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4…
## $ tax <dbl> 296, 242, 242, 222, 222, 222, 311, 311, 311, 311, 311, 311, 3…
## $ ptratio <dbl> 15.3, 17.8, 17.8, 18.7, 18.7, 18.7, 15.2, 15.2, 15.2, 15.2, 1…
## $ black <dbl> 396.90, 396.90, 392.83, 394.63, 396.90, 394.12, 395.60, 396.9…
## $ lstat <dbl> 4.98, 9.14, 4.03, 2.94, 5.33, 5.21, 12.43, 19.15, 29.93, 17.1…
## $ medv <dbl> 24.0, 21.6, 34.7, 33.4, 36.2, 28.7, 22.9, 27.1, 16.5, 18.9, 1…
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
The Boston data frame has 506 rows and 14 columns. All data is numeric. Variables are continuous expect binary variable chas, (“1 if tract bounds Charles River; 0 otherwise”). Response/target variable will be crim (“per capita crime rate by town”), which has range 0.06-89.0 and mean=3.6 & median=0.26. Difference between mean and median suggests strongly skewed distribution.
Descriptives were already shown in step 2. Variable distributions have clearly distinct variances and locations. Some variables seem to be strongly skewed as well. Let’s have a visual.
# Bivariate scatter plots (excluding 4th variable chas)
par(mfrow = c(1,2), pin=c(1.75,1.75))
hist(Boston$crim,col="blue",xlab=NULL)
boxplot(Boston$crim,col="blue", main="Boxplot of Boston$crim")
We can see that crime distribution is strongly skewed. We are going to standardize and categorize variables later.
Pairwise distributions (the plot is enlarged with defining additional R-chunk parameters, which are not shown in output):
# Bivariate scatter plots (excluding 4th variable chas)
pairs(Boston[,c(1:3,5:dim(Boston)[2])], pch=19, cex=0.05, lower.panel=NULL)
Scatter plot matrix shows that bivariate distributions are not always multinormal (or almost never, to be honest). Some distributions do have large empty areas and/or outlier observations, like rad (index of accessibility to radial highways). Not good.
Some mutual bivariate associations seems to be stronger than others. Let’s calculate correlations.
# calculate the correlation matrix and round it
cor_matrix<-cor(Boston) %>% round(digits=2)
# print the correlation matrix
cor_matrix
## crim zn indus chas nox rm age dis rad tax ptratio
## crim 1.00 -0.20 0.41 -0.06 0.42 -0.22 0.35 -0.38 0.63 0.58 0.29
## zn -0.20 1.00 -0.53 -0.04 -0.52 0.31 -0.57 0.66 -0.31 -0.31 -0.39
## indus 0.41 -0.53 1.00 0.06 0.76 -0.39 0.64 -0.71 0.60 0.72 0.38
## chas -0.06 -0.04 0.06 1.00 0.09 0.09 0.09 -0.10 -0.01 -0.04 -0.12
## nox 0.42 -0.52 0.76 0.09 1.00 -0.30 0.73 -0.77 0.61 0.67 0.19
## rm -0.22 0.31 -0.39 0.09 -0.30 1.00 -0.24 0.21 -0.21 -0.29 -0.36
## age 0.35 -0.57 0.64 0.09 0.73 -0.24 1.00 -0.75 0.46 0.51 0.26
## dis -0.38 0.66 -0.71 -0.10 -0.77 0.21 -0.75 1.00 -0.49 -0.53 -0.23
## rad 0.63 -0.31 0.60 -0.01 0.61 -0.21 0.46 -0.49 1.00 0.91 0.46
## tax 0.58 -0.31 0.72 -0.04 0.67 -0.29 0.51 -0.53 0.91 1.00 0.46
## ptratio 0.29 -0.39 0.38 -0.12 0.19 -0.36 0.26 -0.23 0.46 0.46 1.00
## black -0.39 0.18 -0.36 0.05 -0.38 0.13 -0.27 0.29 -0.44 -0.44 -0.18
## lstat 0.46 -0.41 0.60 -0.05 0.59 -0.61 0.60 -0.50 0.49 0.54 0.37
## medv -0.39 0.36 -0.48 0.18 -0.43 0.70 -0.38 0.25 -0.38 -0.47 -0.51
## black lstat medv
## crim -0.39 0.46 -0.39
## zn 0.18 -0.41 0.36
## indus -0.36 0.60 -0.48
## chas 0.05 -0.05 0.18
## nox -0.38 0.59 -0.43
## rm 0.13 -0.61 0.70
## age -0.27 0.60 -0.38
## dis 0.29 -0.50 0.25
## rad -0.44 0.49 -0.38
## tax -0.44 0.54 -0.47
## ptratio -0.18 0.37 -0.51
## black 1.00 -0.37 0.33
## lstat -0.37 1.00 -0.74
## medv 0.33 -0.74 1.00
These are Pearson correlation coefficients, which are not always reliable in a case of non-normality. But let’s keep them anyway, like in Datacamp. However, it’s challenging to assimilate so many numbers. Better to have a visualization.
# installing and/or loading corrplot library for correlation coefficient visualization
if (!require("corrplot")) {
install.packages("corrplot")
library(corrplot)
}
## Loading required package: corrplot
## corrplot 0.84 loaded
# visualize the correlation matrix
corrplot.mixed(cor_matrix, tl.cex=0.75, number.cex=0.75, number.digits=2)
That’s fancy way to present correlation coefficient. We can directly see that there are some strong correlations indicated by big spheres, blue ones for negative and red ones for positive values. Highest value is +0.91, which is between rad and tax (index of accessibility to radial highways and full-value property-tax rate per $10,000).
# center and standardize variables
# 'as.data.frame' is needed since it makes referring variables easier later
boston_scaled <- as.data.frame(scale(Boston))
# Bivariate scatter plots
pairs(boston_scaled, pch=19, cex=0.05, lower.panel=NULL)
#Means, second argument refers to columns
apply(boston_scaled, 2, FUN=mean)
## crim zn indus chas nox
## -7.202981e-18 2.282481e-17 1.595296e-17 -3.544441e-18 -2.150022e-16
## rm age dis rad tax
## -1.056462e-16 -1.643357e-16 1.153079e-16 4.799652e-17 2.024415e-17
## ptratio black lstat medv
## -3.924246e-16 -1.151679e-16 -7.052778e-17 -1.374631e-16
#Variances, second argument refers to columns
apply(boston_scaled, 2, FUN=var)
## crim zn indus chas nox rm age dis rad tax
## 1 1 1 1 1 1 1 1 1 1
## ptratio black lstat medv
## 1 1 1 1
We can see that now all variables has been standardized, i.e. scaled to have mean=0 (or very close to it, at least) and variance=1. This can’t heal difficult distributions like rad or chas has, though. Correlations are the same, so they are not shown here again.
Note: For some reason scaling must be for R data.frame object, otherwise further operations won’t work. This means that command
boston_scaled <- scale(Boston)
is not enought, but I need to put it this way:
boston_scaled <- as.data.frame(scale(Boston)).
So strange… And the same applies for task #7.
Creating categorized version of crime variable. Cut points are quantiles, so number of categories will be four.
# create a quantile vector of crim and print it
bins <- quantile(boston_scaled$crim)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
# create a categorical variable 'crime'
crime <- cut(boston_scaled$crim, breaks=bins, include.lowest=TRUE, labels=c("low","med_low","med_high","high"))
# look at the table of the new factor crime
table(crime)
## crime
## low med_low med_high high
## 127 126 126 127
Looks fine, distribution is as close to 25/25/25/25 percentages as possible.
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)
# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)
Now original crim has been replaced to categorical crime.
# number of rows in the Boston dataset
n <- nrow(boston_scaled)
# choose randomly 80% of the rows
ind <- sample(n, size = n * 0.8)
# create train set
train <- boston_scaled[ind,]
# create test set
test <- boston_scaled[-ind,]
dim(train)
## [1] 404 14
dim(test)
## [1] 102 14
Now datasets train and test has been created, with the first comprising 80% and latter 20% of original cases.
Fitting LDA model on the train set with crime rate categorizations as target variable. Other variables are used as predictors.
# linear discriminant analysis
lda.fit <- lda(crime ~ ., data = train)
# print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2722772 0.2500000 0.2500000 0.2277228
##
## Group means:
## zn indus chas nox rm age
## low 0.9929955 -0.8973507 -0.0933699661 -0.8682868 0.44541544 -0.8892784
## med_low -0.1172657 -0.3372436 0.0005392655 -0.5919780 -0.08760842 -0.4050478
## med_high -0.3836558 0.1911765 0.0785016464 0.3620922 0.05602712 0.4141472
## high -0.4872402 1.0149946 -0.1439453643 0.9941194 -0.33018421 0.8274368
## dis rad tax ptratio black lstat
## low 0.8983361 -0.6811816 -0.7264700 -0.42288990 0.3807021 -0.77122091
## med_low 0.3427051 -0.5520489 -0.5305382 -0.07229914 0.3225662 -0.20206579
## med_high -0.3409828 -0.4201457 -0.3065372 -0.17748551 0.0687396 0.04831993
## high -0.8464439 1.6596029 1.5294129 0.80577843 -0.9177442 0.87984450
## medv
## low 0.51171375
## med_low 0.04293922
## med_high 0.10300978
## high -0.69447449
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.08706752 0.685040094 -0.96286688
## indus 0.01676397 -0.254585080 0.25645666
## chas -0.09876607 0.010888008 0.13254754
## nox 0.20935282 -0.817676888 -1.48888611
## rm -0.09186025 -0.053503551 -0.16727408
## age 0.30917096 -0.266386729 -0.24090394
## dis -0.09872137 -0.301131730 -0.06786035
## rad 3.36001895 1.125208985 0.14461448
## tax 0.08820789 -0.190673085 0.38772976
## ptratio 0.14073960 -0.007337619 -0.36392548
## black -0.15967008 -0.015942660 0.09140325
## lstat 0.21597149 -0.310482850 0.28702042
## medv 0.18438039 -0.471664750 -0.22136817
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9507 0.0371 0.0122
classes <- as.numeric(train$crime)
# LDA (bi)plot
plot(lda.fit, col=classes)
Interestingly plot() function adds group names as data value symbols independently on pch parameters. For example, following commands are yielding identical plots:
- plot(lda.fit, col=classes, pch=19)
- plot(lda.fit, col=classes, pch=classes)
I have no clue why. Showing category value as symbols looks very awkward.
Anyway, plot visualizes how target variable classes are separated by the linear combinations of predictor variables. Looks like crime quantile groups are mostly very nicely separated. High crime group seems to be most consistent while med_high is most scattered around.
Let’s enhance plot by adding arrows into it, just like in Datacamp exercise.
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
plot(lda.fit, col=classes, pch=classes, dimen=2)
lda.arrows(lda.fit, myscale = 2)
Looks like rad (“index of accessibility to radial highways”) is an important factor here. Watch out for living close to radial highways!
# save the correct classes from test data
correct_classes <- test$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime)
# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)
# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 8 9 0 0
## med_low 5 12 8 0
## med_high 0 8 16 1
## high 0 0 1 34
Cross-tabulation shows that in 13+17+15+20 cases (which is 65) prediction is fully correct, leaving out 37 more or less incorrect cases. Proportion of correct predictions is hence 0.6372549. We can see that if prediction has gone wrong, it has still has been mostly placed into category close to the real one. And, we can see that all 20 high crimes cases are correctly predicted. Not bad at all, I guess.
# reloading the Boston dataset
data('Boston')
# standardizing the dataset
# again, as.data.frame is needed, otherwise further operations won't work.
boston_scaled <- as.data.frame(scale(Boston))
# euclidean and manhattan distance matrix
dist_eu <- dist(boston_scaled)
dist_man <- dist(boston_scaled, method="manhattan")
# look at the summaries of the distances
summary(dist_man)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.2662 8.4832 12.6090 13.5488 17.7568 48.8618
summary(dist_man)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.2662 8.4832 12.6090 13.5488 17.7568 48.8618
par(mfrow = c(2,2), pin=c(1.75,1.75))
#Euclidean
hist(dist_eu,col="blue",xlab=NULL)
boxplot(dist_eu,col="blue", main="Boxplot of dist_eu")
#Manhattan
hist(dist_man,col="blue",xlab=NULL)
boxplot(dist_man,col="blue", main="Boxplot of dist_man")
Mean value for Euclidean distance is around 5, range is 0.1 - 14.4. Distribution is slightly skewed to the right.
Mean value for Manhattan distance is around 14, range is 0.3 - 48.9. Distribution is a bit more skewed to the right.
Let’s conduct k-means clustering with three clusters, which, I think, might be good low-but-not-super-low number for centers/clusters.
# k-means clustering with three clusters (=semirandomly selected number)
km <-kmeans(boston_scaled, centers=3)
# plot the Boston dataset with clusters
pairs(boston_scaled, col=km$cluster, pch=19, cex=0.05, lower.panel=NULL)
Three cluster solutions might be plausible. Groups are formed nicely. But let’s see which is optimal number based on calculations.
# Setting a seed for random generator
set.seed(322654435)
# determine the number of clusters
k_max <- 10
# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled, k)$tot.withinss})
# visualize the results
library(ggplot2)
ggplot() +
geom_line(aes(x=1:k_max, y=twcss)) +
scale_x_continuous(breaks=c(1:10)) +
xlab("Number of cluster")
If the principle is that the optimal number of clusters is when the value of total WCSS changes radically, then two clusters would be good choice now. After two clusters total within sum of squares decreased slower. So let’s conduct k-means clustering again, now with two centers, and visulize results.
# k-means clustering
km2 <-kmeans(boston_scaled, centers=2)
# plot the Boston dataset with clusters
pairs(boston_scaled, col=km2$cluster, pch=19, cex=0.05, lower.panel=NULL)
This looks plausible as well. Dot colors indicating cluster seem to mostly create distinct groups in these subplots.
Reloading and scaling Boston data set. AFAIK, this is not needed to done again, but let’s follow instructions. K-means clustering with three center. Fitting LDA with cluster as a target variable, keeping all Boston variables as predictors. Adding arrows with previously created custom function, replacing default red color with blue for better definition. Aspect ratio, text size and arrow length scaling changed from default values as well.
# reloading the Boston dataset
data('Boston')
boston_scaled <- as.data.frame(scale(Boston))
# k-means clustering with three centers
km3 <- kmeans(boston_scaled, centers=3)
km3
## K-means clustering with 3 clusters of sizes 213, 129, 164
##
## Cluster means:
## crim zn indus chas nox rm
## 1 -0.3792002 -0.3640439 -0.2654730 0.004931512 -0.3761109 -0.2611171
## 2 -0.3978261 1.2205329 -0.9803713 -0.028167813 -0.8262430 1.0139959
## 3 0.8054220 -0.4872402 1.1159370 0.015751437 1.1383961 -0.4584605
## age dis rad tax ptratio black
## 1 -0.06380464 0.1123306 -0.5877259 -0.5858342 0.04591154 0.2799627
## 2 -0.90963302 0.9031496 -0.5839140 -0.6780000 -0.82270661 0.3543735
## 3 0.79837224 -0.8562971 1.2226252 1.2941749 0.58749997 -0.6423552
## lstat medv
## 1 -0.09228022 -0.1222510
## 2 -0.94791366 1.0675487
## 3 0.86546676 -0.6809409
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
## 2 1 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2
## 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
## 2 2 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 1
## 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
## 1 1 1 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1
## 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
## 2 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
## 1 1 1 1 1 1 1 3 3 3 1 1 1 1 3 3 3 3 3 3
## 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 1 3
## 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## 1 2 2 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 2
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
## 2 1 2 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
## 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
## 1 1 1 1 2 2 2 1 2 2 1 2 2 2 1 1 1 2 2 2
## 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
## 2 1 2 2 1 1 2 1 2 2 2 2 2 2 2 2 2 2 2 2
## 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
## 2 2 2 2 2 1 2 2 2 1 1 2 1 2 2 2 2 2 2 2
## 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
## 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 2 1 1 2 2
## 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
## 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1
## 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
## 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1
## 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
## 1 2 1 2 2 1 1 2 2 2 2 2 2 2 2 2 3 3 3 3
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
## 3 3 3 3 3 3 3 3 3 3 3 3 3 1 1 1 1 1 1 1
## 501 502 503 504 505 506
## 1 1 1 1 1 1
##
## Within cluster sum of squares by cluster:
## [1] 1083.594 1064.601 1727.469
## (between_SS / total_SS = 45.2 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
# LDA with cluster as a target
lda2.fit <- lda(km3$cluster ~ ., data=boston_scaled)
# print the lda.fit object
lda2.fit
## Call:
## lda(km3$cluster ~ ., data = boston_scaled)
##
## Prior probabilities of groups:
## 1 2 3
## 0.4209486 0.2549407 0.3241107
##
## Group means:
## crim zn indus chas nox rm
## 1 -0.3792002 -0.3640439 -0.2654730 0.004931512 -0.3761109 -0.2611171
## 2 -0.3978261 1.2205329 -0.9803713 -0.028167813 -0.8262430 1.0139959
## 3 0.8054220 -0.4872402 1.1159370 0.015751437 1.1383961 -0.4584605
## age dis rad tax ptratio black
## 1 -0.06380464 0.1123306 -0.5877259 -0.5858342 0.04591154 0.2799627
## 2 -0.90963302 0.9031496 -0.5839140 -0.6780000 -0.82270661 0.3543735
## 3 0.79837224 -0.8562971 1.2226252 1.2941749 0.58749997 -0.6423552
## lstat medv
## 1 -0.09228022 -0.1222510
## 2 -0.94791366 1.0675487
## 3 0.86546676 -0.6809409
##
## Coefficients of linear discriminants:
## LD1 LD2
## crim -0.032231372 -0.180555401
## zn 0.009313889 -1.068645925
## indus 0.624151354 -0.006677424
## chas 0.039930549 0.124911531
## nox 1.097435166 -0.777946957
## rm -0.193309184 -0.586124321
## age -0.164347859 0.406286594
## dis 0.052315163 -0.286780919
## rad 0.701339082 -0.182828969
## tax 1.041861064 -0.515465919
## ptratio 0.245758857 0.034929672
## black -0.020655070 0.015978407
## lstat 0.187227781 -0.395217119
## medv -0.083275066 -0.768211713
##
## Proportion of trace:
## LD1 LD2
## 0.8504 0.1496
# target classes as numeric
classes <- as.numeric(km3$cluster)
# plot the lda results
plot(lda2.fit, col=classes, pch=classes)
# Using previously defined function for lda biplot arrows
lda.arrows(lda2.fit, color="blue", tex=0.8, myscale=5)
Looks like variables nox (nitrogen oxides concentration, parts per 10 million), tax (full-value property-tax rate per $10,000) and zn (proportion of residential land zoned for lots over 25,000 sq.ft) are the most influental separators for the clusters among all variables, based on arrow lengths.
Running the given code for the scaled train data. The code creates a matrix product, which is a projection of the data points. Installing and loading plotly package and creating 3D plots.
Adjusting the code. Defining symbol color as train data set crime class. Drawing another 3D plot where the color is defined by the clusters of the k-means. Plots are only shown in RStudio viewer, so no output in course diary.
# creating train set (again)
train <- boston_scaled[ind,]
#K-means clustering with three centers:
km4 <- kmeans(train, centers=3)
#restoring original crime classification into train data
crime <- cut(train$crim, breaks=bins, include.lowest=TRUE, labels=c("low","med_low","med_high","high"))
#model_predictors <- dplyr::select(train, everything())
model_predictors <- dplyr::select(train, c(-crim))
#dim(model_predictors)
# check the dimensions
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
# installing and/or loading plotly package for 3D plot
if (!require("plotly")) {
install.packages("plotly")
library(plotly)
}
## Loading required package: plotly
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
#Create a 3D plot (Cool!) of the columns of the matrix product by typing the code below.
#plot_ly(x=matrix_product$LD1, y=matrix_product$LD2, z=matrix_product$LD3, type='scatter3d', mode='markers')
#Graph 1
plot_ly(x=matrix_product$LD1, y=matrix_product$LD2, z=matrix_product$LD3, color=crime, type='scatter3d', mode='markers')
## Warning: `arrange_()` is deprecated as of dplyr 0.7.0.
## Please use `arrange()` instead.
## See vignette('programming') for more help
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_warnings()` to see where this warning was generated.
#Graph 2
plot_ly(x=matrix_product$LD1, y=matrix_product$LD2, z=matrix_product$LD3, color=as.factor(km4$cluster), type='scatter3d', mode='markers')
How do plots differ? Well, data points are identical in x-y-z space. Only number of categories/colors (4 vs. 3) differ, so do group distribution. After all, both plots are telling pretty much the same story: there is one clearly distinct blob (upper quartile of crime rates) while rest of dots are somewhat grouped as well. Maybe there is bit more overlapping (variation) in crime category plot.